const express = require("express");
const util = require("../common/util");
const UserDB = require("../model/sqlite/users");
const config = require("../common/config");
/**
 * 获取用户详情
 * @param {express.Request} req
 * @param {express.Response} res
 */
function findById(req, res) {
  (async () => {
    try {
      // 参数校验
      const userId = parseInt(req.params.user_id);
      util.log(`查找用户id为：${userId}的信息`);
      // const userId = parseInt(req.query.id);
      if (isNaN(userId)) {
        return res.status(400).json(util.FormatJSONData(400, "无效的用户ID"));
      }
      const db = UserDB.getInstance();
      await db.connect();
      const user = await db.findById(userId);
      if (!user) {
        return res.status(404).json(util.FormatJSONData(404, "用户不存在"));
      }
      // 敏感字段过滤
      delete user.password;
      delete user.created_ip;
      util.log(`查询用户id为：${userId}的用户名为${user.username}的信息成功`);
      res.json(util.FormatJSONData(200, "获取用户成功", user));
    } catch (err) {
      util.err("查询用户失败");
    }
  })();
}

/**
 * 分页获取用户列表
 * @param {express.Request} req
 * @param {express.Response} res
 */

function findAll(req, res) {
  (async () => {
    try {
      // 参数处理与校验
      const limit = parseInt(req.query.limit);
      const page = parseInt(req.query.page);

      // 如果未传递 limit 或 page，则查询所有用户
      const queryAll = isNaN(limit) || isNaN(page);
      const offset = queryAll ? undefined : (page - 1) * limit;

      if (!queryAll && (limit < 1 || limit > 100)) {
        return res
          .status(400)
          .json(util.FormatJSONData(400, "单页数量限制在1-100之间"));
      }

      const db = UserDB.getInstance();
      await db.connect();

      // 查询所有用户或分页查询
      const users = queryAll
        ? await db.findAll(-1, -1) // 查询所有用户
        : await db.findAll(limit, offset);

      // 打印调试日志
      console.log("原始用户数据:", users);

      // 敏感信息过滤
      const safeUsers = users.map((user) => {
        const { password, created_ip, ...safeData } = user;
        return safeData;
      });

      // 打印调试日志
      console.log("过滤后的用户数据:", safeUsers);

      // 构造返回结果
      res.json(
        util.FormatJSONData(200, "获取用户列表成功", {
          data: safeUsers,
          pagination: queryAll
            ? null // 查询所有时不返回分页信息
            : {
                page,
                limit,
                total: await db.getCount(),
              },
        })
      );
    } catch (err) {
      util.err("获取用户列表失败");
    }
  })();
}

// function findSession(req, res) {
//   (async function () {
//     try {
//         let uid = req.query.user_id;

//     } catch (err) {
//       util.err("创建用户失败");
//     }
//   })();
// }

/**
 * 创建新用户
 * @param {express.Request} req
 * @param {express.Response} res
 */
function add(req, res) {
  (async () => {
    try {
      // 请求体校验
      const requiredFields = ["username", "password"];
      const missing = requiredFields.filter((field) => !req.body[field]);
      if (missing.length > 0) {
        return res
          .status(400)
          .json(
            util.FormatJSONData(400, `缺少必填字段: ${missing.join(", ")}`)
          );
      }
      // 构建用户对象
      const user = {
        username: req.body.username,
        password: util.sha256(req.body.password), // 使用SHA-256加密
        student_id: req.body.student_id,
        real_name: req.body.real_name,
        email: req.body.email,
        phone: req.body.phone,
        avatar_url: req.body.avatar_url,
        role: parseInt(req.body.role) || 1,
        status: parseInt(req.body.status) || 1,
        last_login_time: new Date().toISOString(),
        last_login_ip: util.getReqRemoteIP(req),
        created_ip: util.getReqRemoteIP(req),
        created_at: new Date().toISOString(),
        updated_at: new Date().toISOString(),
      };
      // 唯一性校验
      const db = UserDB.getInstance();
      await db.connect();
      if (await db.findByUsername(user.username)) {
        return res.status(409).json(util.FormatJSONData(409, "用户名已存在"));
      }
      const result = await db.add(user);
      res.status(201).json(
        util.FormatJSONData(201, "用户创建成功", {
          user_id: result,
        })
      );
    } catch (err) {
      util.err("创建用户失败");
    }
  })();
}

/**
 * 更新用户信息
 * @param {express.Request} req
 * @param {express.Response} res
 */
function update(req, res) {
  (async () => {
    try {
      const userId = parseInt(req.body.user_id);
      if (isNaN(userId)) {
        return res.status(400).json(util.FormatJSONData(400, "无效的用户ID"));
      }
      const db = UserDB.getInstance();
      await db.connect();
      const info = await db.findById(userId);
      if (!info) {
        res.status(404).json(util.FormatJSONData(404, "用户不存在"));
      }

      // 构建更新对象
      const updateData = {
        nickname: req.body.nickname ? req.body.nickname : info.nickname,
        student_id: req.body.student_id ? req.body.student_id : info.student_id,
        real_name: req.body.real_name ? req.body.real_name : info.real_name,
        email: req.body.email ? req.body.email : info.email,
        phone: req.body.phone ? req.body.phone : info.phone,
        user_id: parseInt(req.body.user_id),
      };
      const changes = await db.update(updateData);
      if (changes) {
        let result = await db.findById(userId);
        delete result.password;
        req.session.isLogin = true;
        req.session.user = result;
        await new Promise((resolve, reject) => {
          req.session.save((err) => {
            if (err) reject(err);
            else resolve();
          });
        });

        res.json(
          util.FormatJSONData(200, "用户更新成功", {
            info: {
              changes: changes,
              session: req.session,
            },
          })
        );
      }
    } catch (err) {
      util.FormatJSONData(405, "更新用户失败");
    }
  })();
}

function avatar(req, res ){
  (async () => { 
    let uid = parseInt(req.body.user_id);
    let url = req.body.url;
    const db = UserDB.getInstance();
    await db.connect();
    const changes = await db.avatar(uid,url);
    
    if (changes) {
        let result = await db.findById(uid);
        delete result.password;
        req.session.isLogin = true;
        req.session.user = result;
        await new Promise((resolve, reject) => {
          req.session.save((err) => {
            if (err) reject(err);
            else resolve();
          });
        });
        res.json(
          util.FormatJSONData(200, "头像更新成功", {
            info: {
              changes: changes,
              session: req.session,
            },
          })
        );
      }
  })();
}

/**
 * 删除用户
 * @param {express.Request} req
 * @param {express.Response} res
 */
function remove(req, res) {
  (async () => {
    try {
      const userId = parseInt(req.params.user_id);
      if (isNaN(userId)) {
        return res.status(400).json(util.FormatJSONData(400, "无效的用户ID"));
      }
      util.log(`删除用户: ${userId}`);
      const db = UserDB.getInstance();
      await db.connect();
      const changes = await db.remove(userId);
      if (changes === 0) {
        return res.status(404).json(util.FormatJSONData(404, "用户不存在"));
      } else {
        res.json(util.FormatJSONData(204, "用户删除成功", { changes, userId }));
      }
    } catch (err) {
      util.err("删除用户失败");
    }
  })();
}

function register(req, res) {
  (async () => {
    try {
      // 请求体校验
      const requiredFields = ["username", "password"];
      const missing = requiredFields.filter((field) => !req.body[field]);
      if (missing.length > 0) {
        return res
          .status(400)
          .json(
            util.FormatJSONData(400, `缺少必填字段: ${missing.join(", ")}`)
          );
      }
      const timestampPart = Date.now().toString(36);

      // 2. 生成6位随机数字符串（包含大写字母和数字）
      const randomPart = Math.random()
        .toString(36)
        .substring(2, 8)
        .toUpperCase();

      // 3. 组合成最终昵称（使用"用户_"前缀，提高可读性）
      const nickname = `用户_${timestampPart}${randomPart}`;

      // 构建用户对象
      const user = {
        username: req.body.username,
        password: util.md5Pwd(req.body.password),
        student_id: req.body.student_id || null, // ✅ 明确可选字段默认值
        real_name: req.body.real_name || null,
        email: req.body.email || null, // ✅ 即使请求传了，也明确处理（冗余但安全）
        phone: req.body.phone || null,
        avatar_url: config.defaultImg,
        role: parseInt(req.body.role) || 1, // 已有默认值，保留
        status: parseInt(req.body.status) || 1, // 已有默认值，保留
        last_login_time: new Date().toISOString(),
        last_login_ip: util.getReqRemoteIP(req),
        created_ip: util.getReqRemoteIP(req),
        created_at: new Date().toISOString(),
        updated_at: new Date().toISOString(),
        nickname: nickname,
      };
      util.log(user);
      // 唯一性校验
      const db = UserDB.getInstance();
      await db.connect();
      if (await db.findByUsername(user.username)) {
        return res.status(409).json(util.FormatJSONData(409, "用户名已存在"));
      }
      const result = await db.add(user);
      res.status(201).json(
        util.FormatJSONData(201, "用户创建成功", {
          user_id: result,
        })
      );
    } catch (err) {
      util.err("创建用户失败", err);
      res.status(500).json(util.FormatJSONData(500, "服务器内部错误"));
    }
  })();
}

function login(req, res, next) {
  (async () => {
    try {
      const requiredFields = ["username", "password"];
      const missing = requiredFields.filter((field) => !req.body[field]);
      if (missing.length > 0) {
        return res
          .status(200)
          .json(
            util.FormatJSONData(400, `缺少必填字段: ${missing.join(", ")}`)
          );
      }
      const user = {
        username: req.body.username,
        password: util.md5Pwd(req.body.password),
      };
      const db = UserDB.getInstance();
      await db.connect();
      const result = await db.login(user.username, user.password);
      if (!result) {
        return res
          .status(200)
          .json(util.FormatJSONData(401, "用户名或密码错误"));
      } else {
        await db.updateLoginInfo(result.user_id, util.getReqRemoteIP(req));
        delete result.password;
        req.session.isLogin = true;
        req.session.user = result;
        await new Promise((resolve, reject) => {
          req.session.save((err) => {
            if (err) reject(err);
            else resolve();
          });
        });
        // 返回成功响应（Cookie 已通过 Set-Cookie 头自动下发）
        res.status(200).json(
          util.FormatJSONData(200, "登录成功", {
            user: {
              id: result.user_id,
              username: result.username,
              session: req.session,
            },
          })
        );
      }
    } catch (err) {
      util.err("登录失败", err);
      res.status(500).json(util.FormatJSONData(500, "服务器内部错误"));
      next();
    }
  })();
}

function logout(req, res) {
  (async () => {
    try {
      req.session.destroy((err) => {
        if (err) {
          util.err("登出失败");
          res.status(500).json(util.FormatJSONData(500, "服务器内部错误"));
        } else {
          // 清除客户端 Cookie
          res.clearCookie("connect.sid");
          res.status(200).json(util.FormatJSONData(200, "退出成功"));
        }
      });
    } catch (err) {
      util.err("登出失败", err);
      res.status(500).json(util.FormatJSONData(500, "服务器内部错误"));
    }
  })();
}

module.exports = {
  findById,
  findAll,
  add,
  update,
  remove,
  register,
  login,
  logout,
  avatar
};
